const db = require('@root/db')
const path = require('path')
const config = require('@root/config/config')
const querySync = require('@root/db/querySync')
// const querySync = require('../../../db/querySync')
const fs = require('fs')
module.exports = {
  //添加文章
  addArticle(req, res) {
    // 实现思路：通过 express-joi 自动验证 req.body 中的文本数据；通过 if 判断手动验证 req.file 中的文件数据；
    if (!req.file || req.file.fieldname != 'cover_img') {
      res.ms('必须选择封面')
    } else {
      const article = {
        ...req.body,
        author_id: req.auth.id,
        pub_date: new Date(),
        cover_img: path.join(config.cover_img_befapi, req.file.filename)
      }
      db.query(`insert into article set ?`, article, (err, dbRes) => {
        if (err) {
          res.ms(err)
        } else if (dbRes.affectedRows != 1) {
          res.ms('添加失败')
        } else {
          res.ms('ok', 0)
        }
      })
    }
  },
  //根据分类和状态获取文章列表
  getAtrList(req, res) {
    const data = req.query
    let =
      sql = `select * from article where cate_id=? and state=? and author_id=? and is_delete=0`
    let params = [data.cate_id, data.state, req.auth.id]
    if (data.cate_id == '' && data.state) {
      sql = `select * from article where  state=? and author_id=? and is_delete=0`
      params = [data.state, req.auth.id]
    } else if (data.cate_id && data.state == '') {
      sql = `select * from article where cate_id=? and author_id=? and is_delete=0`
      params = [data.cate_id, req.auth.id]
    } else if (data.cate_id == '' && data.state == '') {
      sql = `select * from article where author_id=? and is_delete=0`
      params = [req.auth.id]
    }
    db.query(sql, params, async (err, resList) => {
      if (err) {
        res.ms(err)
      } else {
        if (resList.length == 0) {
          return res.ms('ok', 0, resList)
        }
        let bengin = parseInt(data.pagesize) * (parseInt(data.pagenum) - 1)
        let end = bengin + parseInt(data.pagesize)
        if (bengin > resList.length - 1) {
          return res.ms('ok', 0, [])
        }
        if (end > resList.length) {
          end = resList.length
        }
        // console.log(bengin, end)
        //分页
        const retList = []
        for (let i = bengin; i < end; i++) {
          let item = resList[i]
          //删除文章content
          item.content=undefined
          //添加cate_name
          const { err, resList: resList_catename } = await querySync(
            `select name from article_cate where Id=? and user_id=?`,
            [item.cate_id, req.auth.id]
          )
          if (err) {
            res.ms(err)
          } else {
            item['cate_name'] = resList_catename[0].name
            retList.push(item)
          }
        }
        res.ms('ok', 0, retList)
      }
    })
  },
  //删除文章
  async delArticle(req, res) {
    const id = req.params.id
    const { err, resList } = await querySync(
      `update article set is_delete=1 where Id=? and author_id=?`,
      [id, req.auth.id]
    )
    if (err) return res.ms(err)

    if (resList.affectedRows != 1) return res.ms('删除失败')

    res.ms('ok', 0)
  },
  //根据 Id 获取文章详情
  async getArtInfo(req, res) {
    const { err, resList } = await querySync(
      `select * from article where Id =? and author_id=?`,
      [req.params.id, req.auth.id]
    )
    if (err) return res.ms(err)

    res.ms('ok', 0, resList)
  },
  // 根据 Id 更新文章信息
  async updateArtInfo(req, res) {
    if (!req.file || req.file.fieldname != 'cover_img') {
      return res.ms('必须选择封面')
    }

    //删除原图片
    db.query(
      'select * from article where Id=? and author_id=?',
      [req.body.Id, req.auth.id],
      (err, resList) => {
        if (err) {
          console.log('sql删除原图片失败')
        } else {
          const filename = resList[0].cover_img.split('\\')[1]
          fs.unlink('static/img/' + filename, (err) => {
            console.log('fs删除原图片失败')
          })
        }
      }
    )

    const articleInfo = {
      ...req.body,
      cover_img: path.join(config.cover_img_befapi, req.file.filename)
    }

    const { err, resList } = await querySync(
      'update article set ? where Id=? and author_id=?',
      [articleInfo, articleInfo.Id, req.auth.id]
    )
    if (err) return res.ms(err)
    if (resList.affectedRows != 1) return res.ms('更新失败')
    res.ms('ok', 0)
  }
}
